import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {FormBuilder, FormControl, Validators} from '@angular/forms';
import {TurbStatus} from '../../../../entity/turbstatus.model';
import {Command} from '../../../../shared/toolbar.service';
import {TurbStatusService} from '../../../../service/turbstatus.service';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';

import {MyValidators} from '../../../../utils/validator/rang';

import {DeviceCategory} from '../../../../entity/device-category.model';
import {DeviceCategoryService} from '../../../../service/device-category.service';

@Component({
    selector: 'app-turbstatus-edit',
    templateUrl: './turbstatus-edit.component.html',
    styleUrls: ['./turbstatus-edit.component.css']
})
export class TurbstatusEditComponent extends BladeContainerBase<TurbStatus> {
    // private emailTimeout;
    colorOut: {};
    public deviceCategorys: DeviceCategory[] = [];
    private originalDeviceCategory: DeviceCategory[] = [];

    constructor(
        private fb: FormBuilder,
        private turbastatusService: TurbStatusService,
        private dviceCategoryService: DeviceCategoryService
    ) {
        super(fb);
    }
    // tslint:disable-next-line:use-life-cycle-interface
    ngOnInit(): void {
        // 编辑时注册按钮和按钮命令
        this.initDevice();
        if (!this.isNew) {
            this.commands = [
                // tslint:disable-next-line:max-line-length
                new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
                new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
            ];
        } else {
            this.currentEntity = new TurbStatus(0, '', '', '', 1);
        }
        super.ngOnInit();
    }
    /**
     * 初始化数据
     *
     *
     * @memberof TurbstatusValueListComponent
     */
    initData(): any | Observable<any> | Promise<any> {
        this.formPatchValue(this.currentEntity);

    }
    exeSaveChange(blade: any): void {
        this.saveChange();
    }
    canSaveChange(blade: any): boolean {
        return this.hasChange() && !this.hasError();
    }
    exeReset(blade: any): void {
        return this.formGroup.reset(this.currentEntity);
    }
    canReset(blade: any): boolean {
        return this.hasChange();
    }
    initDevice() {
        this.dviceCategoryService.getDeviceCategorys()
            .then(res => {
                if (res) {
                    this.originalDeviceCategory = [...res];
                    this.deviceCategorys = this.originalDeviceCategory;
                }
            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false);
    }
    /**
    * 创建表单
    *
    *
    * @memberof DicKeyEditComponent
    */
    createForm() {
        this.formGroup = this.fromBuider.group({
            'statusName': [this.currentEntity.statusName, [
                Validators.required,
                Validators.pattern('^[\u4e00-\u9fa5a-zA-Z0-9]+$'),
                Validators.maxLength(50),
            ], (control: FormControl): any => this.statusAsnyValidator(control, 'statusName', this.currentEntity.statusName)
            ],
            'statusKey': [this.currentEntity.statusKey, [
                Validators.required,
                Validators.pattern('^[A-Za-z0-9]+$'),
                Validators.maxLength(20)
            ], (control: FormControl): any => this.statusAsnyValidator(control, 'statusKey', this.currentEntity.statusKey)
            ],
            'statusValue': [this.currentEntity.statusValue, [
                Validators.required,
                MyValidators.rang(0, 255)
            ], (control: FormControl): any => this.statusAsnyValidator(control, 'statusValue', this.currentEntity.statusValue)
            ],
            'statusColor': [this.currentEntity.statusColor, [
                Validators.required,
                Validators.pattern('^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$'),
                Validators.maxLength(7)
            ], (control: FormControl): any => this.statusColorAsnyValidator(control)],
            'statusColor2': [this.currentEntity.statusColor],
            'priority': [this.currentEntity.priority, [
                Validators.required,
                MyValidators.rang(0, 255)
            ], (control: FormControl): any => this.statusAsnyValidator(control, 'priority', this.currentEntity.priority)
            ],
            'statusSeq': [this.currentEntity.statusSeq, [
                Validators.required,
                MyValidators.rang(0, 255)
            ]
            ],
            'deviceCategoryId': [this.currentEntity.deviceCategoryId, [
                Validators.required,
            ]
            ],
        });
        this.formGroup.controls['statusColor2'].valueChanges.subscribe(form => {
            if (this.formGroup.controls['statusColor'].value !== form) {
                this.formGroup.controls['statusColor'].setValue(form);
            }

        });
        this.formGroup.controls['statusColor'].valueChanges.subscribe(form => {
            if (this.formGroup.controls['statusColor2'].value !== form) {
                this.formGroup.controls['statusColor2'].setValue(form);
            }
        });
    }
    /**
    * 设置表单错误对象
    *
    *
    * @memberof BladeContainerBase
    */
    setFormError(): void {
        this.formErrors = {
            'statusName': '',
            'statusKey': '',
            'statusValue': '',
            'statusColor': '',
            'priority': '',
            'statusSeq': '',
            'deviceCategoryId': ''
        };
    }
    /**
    * 设置表单验证信息
    *
    *
    * @memberof BladeContainerBase
    */
    setValidationMessages(): void {
        this.validationMessages = {
            'statusName': {
                'required': '状态名称不能为空。',
                'pattern': '状态名称必须是汉字字母数字。',
                'maxlength': '状态名称不能多于50个字符长度。',
                'exist': '状态名称已存在。',
            },
            'statusKey': {
                'required': '状态标识不能为空。',
                'pattern': '状态名称必须是英文数字组成。',
                'maxlength': '状态标识不能多于20个字符长度。',
                'exist': '状态标识已存在。',
            },
            'statusValue': {
                'required': '状态值不能为空。',
                'rang': '状态值范围是0~255。',
                'exist': '状态值已存在。',
            },
            'statusColor': {
                'required': '颜色值不能为空。',
                'pattern': '颜色值只能是以#开头的数字字母。',
                'maxlength': '颜色值只能是7个字符长度。',
                'exist': '颜色值已存在。',
            },
            'priority': {
                'required': '优先级值不能为空。',
                'rang': '优先值范围是0~255。',
                'exist': '优先级值已存在。',
            },
            'statusSeq': {
                'required': '排序值不能为空。',
                'rang': '排序值范围是0~255。',
            },
            'deviceCategoryId': {
                'required': '请选择设备。',
            }
        };
    }

    /**
     * 异步校验status是否存在
     *
     * @param {FormControl} control
     * @returns {Promise<true>}
     *
     * @memberof turbstatusEditComponent
     */
    statusAsnyValidator(control: FormControl, name: string, current: any): any {
        if (!control.value || control.value == current) {
            return Observable.of(null);
        }
        return this.turbastatusService.hasStatusName(control.value, this.currentEntity.statusId, name)
            .map(res => res ? { exist: true } : null);
    }
    /**
     * 异步校验statusColor是否存在
     *
     * @param {FormControl} control
     * @returns {Promise<true>}
     *
     * @memberof turbstatusEditComponent
     */
    statusColorAsnyValidator(control: FormControl): any {
        if (control.value == this.currentEntity.statusColor) {
            return Observable.of(null);
        }
        return this.turbastatusService.hasStatusColor(control.value, this.currentEntity.statusId)
            .map(res => res ? { exist: true } : null);
    }
    /**
     * 创建一个风机状态
     *
     *
     * @memberof TurbstatusEditComponent
     */
    onCreate() {
        if (!this.hasError()) {
            this.changeCurrent();
            this.turbastatusService.create(this.currentEntity)
                .then(res => {
                    if (res.statusId) {
                        const parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }
    /**
     *
     *
     *
     * @memberof TurbstatusEditComponent
     */
    saveChange(): any | Promise<any> | Observable<any> {

        if (this.canSaveChange(this.currentBlade)) {
            this.changeCurrent();
            return this.turbastatusService.update(this.currentEntity)
                .then(res => {
                    if (res) {
                        (this.parentBlade.bladeContainerInstance).refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }
    changeCurrent() {
        this.bladeData.isLoading = true;
        const formValue = this.formGroup.value as TurbStatus;
        this.currentEntity.statusName = formValue.statusName;
        this.currentEntity.statusKey = formValue.statusKey;
        this.currentEntity.statusValue = formValue.statusValue;
        this.currentEntity.statusColor = formValue.statusColor;
        this.currentEntity.priority = formValue.priority;
        this.currentEntity.statusSeq = formValue.statusSeq;
        this.currentEntity.deviceCategoryId = formValue.deviceCategoryId;
    }
    recPro(event: {}) {
        this.colorOut = event;
    }
    // tslint:disable-next-line:eofline
}


// WEBPACK FOOTER //
// ./src/app/module/basic/turbstatus/turbstatus-edit/turbstatus-edit.component.ts
